<template>
  <Form :validation-schema="mySchema" autocomplete="off" v-slot="{errors}" class="xtx-form" ref="formCom">
    <div class="user-info">
      <img :src="avatar" alt=""/>
      <p>Hi，{{ nickname }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field v-model="form.mobile" name="mobile" class="input" type="text" placeholder="绑定的手机号"
               :class="{err:errors.mobile}"/>
      </div>
      <div v-if="errors.mobile" class="error"><i class="iconfont icon-warning"/> {{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field v-model="form.code" name="code" class="input" type="text" placeholder="短信验证码"
               :class="{err:errors.code}"/>
        <span class="code" @click="send">{{ time === 0 ? '发送验证码' : `${time}秒后发送` }}</span>
      </div>
      <div v-if="errors.code" class="error"><i class="iconfont icon-warning"/> {{ errors.code }}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit">立即绑定</a>
  </Form>
</template>

<script>
import QC from 'qc'
import { reactive, ref } from 'vue'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import Message from '@/components/library/Message'
import { useIntervalFn } from '@vueuse/core'

export default {
  name: 'CallbackBind',
  components: {
    Form,
    Field
  },
  props: {
    unionId: {
      type: String,
      default: null
    }
  },
  setup (props) {
    //  1、准备一下消息： unionId(openId) qq头像 昵称
    const nickname = ref('null')
    const avatar = ref('null')
    if (QC.Login.check()) {
      QC.api('get_user_info').success(res => {
        console.log(res)
        nickname.value = res.data.nickname
        avatar.value = res.data.figureurl_2
      })
    }
    //  2. 完成表单校验
    // 表单数据对象
    const form = reactive({
      mobile: null,
      code: null
    })
    // 校验规则对象
    const mySchema = {
      mobile: schema.mobile,
      code: schema.code
    }
    //  3.发送验证码（校验，定义API，调用，完成倒计时）
    // 发送短信验证码
    // pause 暂停 resume 开始
    // useIntervalFn(回调函数,执行间隔,是否立即开启)
    const time = ref(0)
    const {
      pause,
      resume
    } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, false)
    const send = () => {
      // 返回校验消息: 成功===>true  失败===>错误的提示字符串
      const valid = mySchema.mobile(form.mobile)
      if (valid === true) {
        // 校验通过
        if (time.value === 0) {
          // 没有倒计时才可以发送
          userQQBindCode(form.mobile).then(res => {
            console.log(res)
            Message({
              type: 'success',
              text: '短信发送成功'
            })
            // 倒计时60秒
            time.value = 60
            // 开启定时器
            resume()
          }).catch(e => {
            console.log(e)
            if (e.response.data) {
              Message({
                type: 'error',
                text: e.response.data.message || ' 短信发送失败'
              })
            }
          })
        }
      } else {
        // 校验失败: 使用vee的错误函数显示错误消息 setFieldError(字段名称,错误消息)
        formCom.value.setFieldError('mobile', valid)
      }
    }
    //  4.进行绑定（绑定成功就是登录成功）
    const formCom = ref(null)
    const store = useStore()
    const router = useRouter()
    const submit = () => {
      const valid = formCom.value.validate()
      if (valid) {
        userQQBindLogin({ unionId: props.unionId, ...form }).then(data => {
          console.log(data)
          // 1.存储用户消息
          const {
            id,
            account,
            nickname,
            avatar,
            token,
            mobile
          } = data.data.result
          store.commit('user/setUser', {
            id,
            account,
            nickname,
            avatar,
            token,
            mobile
          })
          // 合并购物车
          store.dispatch('cart/mergeCart').then(() => {
            // 2.跳转到来源页或者首页
            router.push(store.state.user.redirectUrl || '/')
            // 3.成功提示
            Message({
              type: 'success',
              text: '完善信息成功'
            })
          })
        }).catch(err => {
          console.log(err)
          if (err.response) {
            Message({
              type: 'error',
              text: err.response.data.message || '登录失败'
            })
          }
        })
      }
    }
    return {
      nickname,
      avatar,
      form,
      formCom,
      mySchema,
      time,
      submit,
      send
    }
  }
}
</script>

<style scoped lang='less'>
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;

  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }

  p {
    padding-left: 10px;
  }
}

.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;

  &:hover {
    cursor: pointer;
  }
}
</style>
